<?php
/************************************************************************
 Omnitrix - PHP Development Framework
 Copyright (C) 2012-2018 amonest(eastson@outlook.com)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
************************************************************************/

class omnitrix_tree
{
	private $_data = array();
	private $_child = array(-1=>array());
	private $_layer = array(-1=>-1);
	private $_parent = array();

	public function __construct()
	{
		$this->add_node(0, -1, null);
	}

	public function add_node($id, $parent, $value)
	{
		$parent = $parent ? $parent : 0;

		$this->_data[$id] = $value;
		$this->_child[$id] = array();
		$this->_child[$parent][] = $id;
		$this->_parent[$id] = $parent;

		if (!isset($this->_layer[$parent])) {
			$this->_layer[$id] = 0;
		} else {
			$this->_layer[$id] = $this->_layer[$parent] + 1;
		}
	}

	public function get_list(&$tree, $root= 0)
	{
		foreach ($this->_child[$root] as $key => $id) {
			$tree[] = $id;

			if ($this->_child[$id]) {
				$this->get_list($tree, $id);
			}
		}
	}

	public function get_value($id)
	{
		return $this->_data[$id];
	}

	public function get_layer($id, $space = false)
	{
		return $space ? str_repeat($space, $this->_layer[$id]) : $this->_layer[$id];
	}

	public function get_parent($id)
	{
		return $this->_parent[$id];
	}

	public function get_parents($id)
	{
		while ($this->_parent[$id] != -1) {
			$id = $parent[$this->_layer[$id]] = $this->_parent[$id];
		}

		ksort($parent);
		reset($parent);

		return $parent;
	}

	public function get_child($id)
	{
		return $this->_child[$id];
	}

	public function get_childs($id = 0)
	{
		$child = array($id);
		$this->get_list($child, $id);

		return $child;
	}
}